package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealCheckgroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealCheckgroupMapper setmealCheckgroupMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Configuration configuration;
    @Value("${freemarker.out.path}")
    private String outPath;
    /**
     * 根据查询条件分页查询体检套餐
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        // 根据id查询套餐
        Setmeal setmeal = setmealMapper.findById(id);
        return setmeal;
    }

    /**
     * 新增套餐
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    public void add(List<Integer> checkgroupIds, Setmeal setmeal) {
        // 向套餐表插入数据，并主键返回套餐id
        setmealMapper.add(setmeal);

        // 套餐数据插入到数据库后，将图片名称保存到redis的另一个集合
        SetOperations set = redisTemplate.opsForSet();
        set.add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        //根据套餐id和检查组id列表向套餐检查组中间表批量插入数据
        Integer setmealId = setmeal.getId();
        setmealCheckgroupMapper.addBatch(checkgroupIds, setmealId);
        // 添加套餐后使用模版生成静态页面
        generateMobileSaticHtml();
    }

    /**
     * 生成静态页面
     */
    private void generateMobileSaticHtml() {
        // 1 获取所有的数据
        List<Setmeal> setmealList = setmealMapper.getAllSetmeal();
        // 2 生成套餐列表静态数据
        generateSetmealListSaticHtml(setmealList);
        // 3 生成套餐详情静态页面（多个）
        generateSetmealDetailStaticHtml(setmealList);
    }

    /**
     * 生成套餐列表静态页面
     * @param setmealList
     */
    private void generateSetmealListSaticHtml(List<Setmeal> setmealList) {
        try {
            // 1 获取Freemarker模版
            Template template = configuration.getTemplate("mobile_setmeal.ftl");
            // 用于存放套餐列表
            Map<String, Object> map = new HashMap<>();
            // 2 将套餐列表放入map集合
            map.put("setmealList", setmealList);
            try (
                    FileWriter out = new FileWriter(outPath + "\\m_setmeal.html");
                    ){
                // 3 生成套餐列表静态页面
                template.process(map, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成套餐详情静态页面（多个）
     * @param setmealList
     */
    private void generateSetmealDetailStaticHtml(List<Setmeal> setmealList) {
        try {
            Template template = configuration.getTemplate("mobile_setmeal_detail.ftl");
            if (setmealList != null && setmealList.size() > 0){
                for (Setmeal setmeal : setmealList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("setmeal", setmealMapper.getById(setmeal.getId()));
                    try {
                        FileWriter out = new FileWriter(outPath + "\\setmeal_detail_" + setmeal.getId() + ".html");
                        template.process(map, out);
                    } catch (TemplateException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑套餐
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    public void edit(List<Integer> checkgroupIds, Setmeal setmeal) {
        // 在更新前根据套餐id查询图片
        String preImg = setmealMapper.findById(setmeal.getId()).getImg();
        // 更新套餐表数据
        setmealMapper.edit(setmeal);

        // 新图片
        String newImg = setmeal.getImg();
        // 套餐数据插入到数据库后，将图片名称保存到redis中 同时用新图片替换旧图片
        SetOperations set = redisTemplate.opsForSet();
        set.remove(RedisConstant.SETMEAL_PIC_DB_RESOURCES, preImg);
        set.add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, newImg);

        // 根据套餐id删除套餐检查组中间表数据
        Integer setmealId = setmeal.getId();
        setmealCheckgroupMapper.deleteBySetmealId(setmealId);
        // 批量向套餐检查组中间表插入数据
        setmealCheckgroupMapper.addBatch(checkgroupIds, setmealId);
    }
}
